package com.calvin.study.service.sys.security;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.calvin.study.mapper.sys.SysUserMapper;
import com.calvin.study.model.sys.SysUser;

@Service
public class MyUserDetailsService implements UserDetailsService {

	@Resource
	SysUserMapper sysUserMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		SysUser sysUser = sysUserMapper.findByUserName(username);
		if(null == sysUser) {
			throw new UsernameNotFoundException("该用户不在");
		}
		//查询该用户拥有的角色
		List<String> roleCodes = sysUserMapper.findRoleByUserName(username);
		//该用户角色对应的权限资源集合
		List<String> authorities = sysUserMapper.findAuthByRoleCodes(roleCodes);

		// 在每个rolecode前面添加上"ROLE_"，最终"ROLE_admin"
		roleCodes = roleCodes.stream().map(rc -> "ROLE_" + rc).collect(Collectors.toList());
		
		authorities.addAll(roleCodes);
		List<GrantedAuthority> gauthorities = AuthorityUtils.commaSeparatedStringToAuthorityList(String.join(",", authorities));
		User user = new User(sysUser.getUserName(), sysUser.getPassword(), sysUser.getEnabled(), true, true, true, gauthorities);
		return user;
	}
	
	public static void main(String[] args) {
		Set<String> submits = new HashSet<String>();
		submits.add("一");
		submits.add("二");
		submits.add("三");
		submits.add("四");
		submits.add("五");
		//submits = submits.stream().map(sb -> sb + "、").collect(Collectors.toSet());
		
		String aa  = submits.stream().map(String::valueOf).collect(Collectors.joining("、"));
		System.out.println(aa);
		
		
		List<String> users = new LinkedList<>();
	    users.add("小明");
	    users.add("小红");
	    users.add("小兰");
	    users.add("小兰");
	    users.add("小兰");
	    
	    // 根据 name 进行去重
	    List<String> userList = users.stream()
	        .collect(Collectors.collectingAndThen(
	            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(String::valueOf))),
	            ArrayList::new)
	        );
	    
		String strUser  = userList.stream().map(String::valueOf).collect(Collectors.joining("、"));
	    System.out.println(strUser);
	}

}
